<?php

if(PARCL_EXEC !== 1) {
    die('<h1>Incorrect Access</h1>You cannot access this file directly.<br/>' .
         'If you got this error message by clicking a link on the site,' .
         'please notify the webmaster as soon as possible.');
}

/**
 * Purpose     : The user management module.
 * Description : Contains the generic methods for user management.
 */

class Users {
	private $switch;
	
    public function __construct() {
		$this->switch = (array_key_exists('switch', $_GET) ? StringTools::MoldEntry($_GET['switch'], 1, 16) : null);
	}

    /**
     * Input       : $id: Integer containing the ID of the article you want to retrieve.
     * Output      : $article: A properly formed array ready for template parsing.
     * Description : This function does everything necessary to properly generate
                     the article array and preparing the result-set returned to a
                     template parsable array.
     * Errors      : None.
     * Assumptions : That $id is an integer.
     * Dev Notes   : Lots of things to be done here.
     */
    public function Execute($mode) {
		if($switch == 'login') {
			$userName = (array_key_exists('userName', $_POST) ? trim($_POST['userName']) : null);
			$password = (array_key_exists('password', $_POST) ? $_POST['password'] : null);
			$error = null;
			$output = null;

			$userName = StringTools::MoldEntry($userName, 1, 20);
			$password = StringTools::MoldEntry($password, 1, 20);

			if(empty($userName) && empty($password)) {
				$error = 'Enter username and password.';
			}
			elseif(empty($userName)) {
				$error = 'Enter username.';
			}
			elseif(empty($password)) {
				$error = 'Enter password.';
			}
			elseif(!($user = UsersQueries::GetUser(mb_strtolower($userName), Crypto::hash($password)))) {
				$error = 'Invalid user/password combination.';
			}
			if(!is_null($error)) {
				$output['error'] = $error;
			}
			else {
				$_SESSION['loggedIn'] = true;
				$_SESSION['userName'] = $user['username'];
				$output['success'] = 'Logged in successfully.';
			}
			return $output;
		}
		elseif($switch == 'logout') {
			$_SESSION = array();
			if(isset($_COOKIE[session_name()])) {
				setcookie(session_name(), '', time() - 42000, '/');
			}
			session_destroy();
			return $output['success'] = 'Logged out successfully.';
		}

		if(@$_SESSION['loggedIn']) {
			$output['user'] = 'Welcome, ' . $_SESSION['userName'] . '.';
		}
		else {
			$output['user'] = 'If you have an account, please log in here. If you do not, head over to the forums to register there.';
			$output['loginBox'] = '';
		}

        return $output;
    }
}